package agriculture.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ 基本交换机、队列、路由配置
 */
@Configuration
public class RabbitMQConfig {
    //支付配置
    public static final String EXCHANGE_NAME = "order.exchange";
    public static final String QUEUE_NAME = "order.paid.queue";
    public static final String ROUTING_KEY = "order.paid";

    // --- 新增延迟取消订单配置 ---
    public static final String DELAY_QUEUE_NAME = "order.delay.queue";
    public static final String DEAD_QUEUE_NAME = "order.dead.queue";
    public static final String DEAD_ROUTING_KEY = "order.dead";

    /**
     * 主交换机（支付成功通知、订单延迟取消都共用）
     */
    @Bean
    public TopicExchange orderExchange() {
        return new TopicExchange(EXCHANGE_NAME, true, false);
    }

    /**
     * 支付成功队列
     */
    @Bean
    public Queue orderPaidQueue() {
        return new Queue(QUEUE_NAME, true);
    }

    /**
     * 支付成功绑定关系
     */
    @Bean
    public Binding binding() {
        return BindingBuilder
                .bind(orderPaidQueue())
                .to(orderExchange())
                .with(ROUTING_KEY);
    }
    /**
     * 延迟队列（消息延迟15分钟后转发到死信队列）
     */
    @Bean
    public Queue orderDelayQueue() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", EXCHANGE_NAME); // 死信交换机
        args.put("x-dead-letter-routing-key", DEAD_ROUTING_KEY); // 死信 routing key
        args.put("x-message-ttl", 15 * 60 * 1000); // 15分钟超时（毫秒）
        return new Queue(DELAY_QUEUE_NAME, true, false, false, args);
    }

    /**
     * 死信队列（接收延迟消息）
     */
    @Bean
    public Queue orderDeadQueue() {
        return new Queue(DEAD_QUEUE_NAME, true);
    }

    /**
     * 绑定延迟队列
     */
    @Bean
    public Binding delayBinding() {
        return BindingBuilder
                .bind(orderDelayQueue())
                .to(orderExchange())
                .with("order.delay"); // 自定义 delay routing key
    }

    /**
     * 绑定死信队列
     */
    @Bean
    public Binding deadBinding() {
        return BindingBuilder
                .bind(orderDeadQueue())
                .to(orderExchange())
                .with(DEAD_ROUTING_KEY);
    }
}
